package me.stone.stanimeclient.core.ui.item

import android.content.Context
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import me.stone.stanimeclient.core.common.di.ApplicationScope
import me.stone.stanimeclient.core.model.FanMimeData
import me.stone.stanimeclient.core.ui.R
import javax.inject.Inject


class FanMimeDataBindingHelper @Inject constructor(
    @ApplicationContext context: Context,
    @ApplicationScope private val coroutineScope: CoroutineScope
) {

    private val defMimeData = FanMimeData(
        id = 0, cover = "", latestEpisode = "",
        name = "数据加载中...", originalName = "数据加载中...",
        area = "地区", status = "类型", writer = "作者", type = "状态",
        premiere = "数据加载中...", tags = "数据加载中...",
        company = "数据加载中...", intro = "数据加载中..."
    )

    private val _fanMimeData = MutableStateFlow(defMimeData)

    val fanMimeData: StateFlow<FanMimeData> = _fanMimeData

    val foldLabelData: IToggleText = FoldLabelData(context, coroutineScope)

    fun updateFanMimeData(fanMimeData: FanMimeData) {
        coroutineScope.launch { _fanMimeData.emit(fanMimeData) }
    }

    private class FoldLabelData(
        context: Context,
        private val coroutineScope: CoroutineScope
    ) : IToggleText {

        private val close = context.buildToggleText(
            R.string.fold_close, R.drawable.ic_player_minimize
        )

        private val open = context.buildToggleText(
            R.string.fold_open, R.drawable.ic_player_maximize
        )

        private val _close = MutableStateFlow(true)

        override val label: StateFlow<CharSequence>
            get() = _close
                .map { if (it) open else close }
                .stateIn(coroutineScope, SharingStarted.Eagerly, "")

        override val state: StateFlow<Boolean>
            get() = _close
                .stateIn(coroutineScope, SharingStarted.Eagerly, true)

        override fun toggle() {
            val newValue = !_close.value
            coroutineScope.launch {
                _close.emit(newValue)
            }
        }

    }
}